var db     = require('../config/mongo_database');
var log    = require('../route/log');
var logger = require('../config/log4js').logger('access');

// 新增订单
/**
	userid  用户id
	type    支付币种
	content 充值，活动扣款，提现
	trade   【0待充值】【1确认中】【2交易成功】
	detail  详情对象

**/
exports.addOrder = function(detail, callback) {
	var order       = new db.orderModel();
	order.orderid   = detail.orderid
	order.userid    = detail.userid 
	order.type      = detail.type
	order.btype     = detail.btype
	order.pay       = detail.pay
	order.content   = detail.content
	order.trade     = detail.trade
	order.detail    = detail.detail
	
    order.save(function(err) {
    	if(err){
    		logger.error('property.addOrder', detail)
    		callback(false)
    	}else{
    		callback(true)
    	}
	});
};


// 新增对账单
exports.addBalance = function(detail, callback) {
	var balance      = new db.balanceModel();
	balance.orderid  = detail.orderid 
	balance.userid   = detail.userid 
	balance.username = detail.username  
	balance.nick     = detail.nick || ''
	balance.btype    = detail.btype          // 币种类型
	balance.type     = detail.type           // 购买 1 充值 2提现 3赎回到账
	balance.content  = detail.content || ''
	balance.pay      = detail.pay
	balance.countn   = detail.countn
	balance.saddr    = detail.saddr || ''   //  发送地址
	balance.raddr    = detail.raddr || ''   //  接收地址
	balance.flag     = detail.flag  || ''   //  标识
	balance.ps       = detail.ps    || '0'  //  0 转入， 1转出
	balance.status   = detail.status || '0'
     
    balance.save(function(err) {
    	if(err){
    		logger.error('property.addBalance', detail)
    		log.addLog(detail.userid, '新增对账单失败', detail)
    		callback(false)
    	}else{
    		callback(true)
    	}
	});
};


/** 查询钱包并更新
**  userid 用户id, btype 币种类型
**/
exports.findNewWallet = function(detail){
	db.walletModel.findOne({userid:detail.userid, btype:detail.btype}, function(err, wallet){
		if(wallet==null){
			logger.info('为用户生成一个钱包', detail.userid, detail.btype)
			var wallet = new db.walletModel();
			wallet.userid   = detail.userid
			wallet.username	= detail.username
			wallet.btype	= detail.btype

			wallet.save(function(err) {
		    	if(!err)
		    		logger.info('新建钱包成功: ', detail.userid, ':btype:', detail.btype)
			});
		}
	})
}

// 查询币种钱包列表
exports.bcoinlist = function(req, res){
	db.bcoinModel.find({status:'1'}, function(err, list){
		return res.json({status:200, msg:'钱包列表', list:list})
	})
}


// 扣除钱包金额
exports.outWallet = function(detail){
	db.walletModel.update({userid:detail.userid, btype:detail.btype}, {$inc: {asset:detail.pay*(-1)}}, function(err){
		if(err){
			logger.error(detail.userid, '扣除金额失败', detail.pay, detail.btype)
			log.addLog(detail.userid, '扣除金额失败', detail)
		}
	})
}










